﻿@using SimpleIdServer.IdServer.Website.Resources;
@using SimpleIdServer.IdServer.Website.Stores.ScopeStore;
@using SimpleIdServer.IdServer.Website.Stores.UserStore;
@inherits Fluxor.Blazor.Web.Components.FluxorComponent
@inject ContextMenuService contextMenuService
@inject DialogService dialogService
@inject IDispatcher dispatcher
@inject IUrlHelper urlHelper
@inject IState<ScopeMappersState> scopeMappersState
@inject NotificationService notificationService

<SidAuthorizeView Roles=@($"/scopes/manage")>
    <Authorized>
        <RadzenButton class="mb-1" Click="@(args => AddMapper())" Icon="add" Text="@Global.AddMapper" ButtonStyle="ButtonStyle.Primary" Size="ButtonSize.Medium"></RadzenButton>
    </Authorized>
</SidAuthorizeView>

<RadzenDataGrid AllowFiltering="true"
                AllowColumnResize="true"
                AllowAlternatingRows="false"
                AllowSorting="true"
                PageSize="30"
                AllowPaging="true"
                PagerHorizontalAlign="HorizontalAlign.Left"
                ShowPagingSummary="true"
                IsLoading="false"
                RowRender="@RowRender"
                Count="@scopeMappersState.Value.Count"
                Data="@scopeMappersState.Value.Mappers"
                TItem="SelectableScopeMapper"
                ColumnWidth="300px">
    <Columns>
        <RadzenDataGridColumn TItem="SelectableScopeMapper" Filterable="false" Sortable="false" Width="80px" TextAlign="TextAlign.Center">
            <HeaderTemplate>
                <RadzenCheckBox @bind-Value=@selectAll Change="@(args => ToggleAll(args))" TValue="bool" />
            </HeaderTemplate>
            <Template Context="data">
                <RadzenCheckBox @bind-Value=@data.IsSelected Change="@(args => ToggleChanged(args, data))" TValue="bool" />
            </Template>
        </RadzenDataGridColumn>
        <RadzenDataGridColumn TItem="SelectableScopeMapper" Title="@Global.Name" Filterable="false" Sortable="true" Width="80px" SortOrder="SortOrder.Ascending">
            <Template Context="data">
                <RadzenLink Text="@data.Value.Name" Path="@(urlHelper.GetUrl($"/scopes/{Scope.Id}/mappers/" + data.Value.Id))" />
            </Template>        
        </RadzenDataGridColumn>
        <RadzenDataGridColumn TItem="SelectableScopeMapper" Title="@Global.Type" Filterable="false" Sortable="false" Width="80px">
            <Template Context="data">
                @switch (data.Value.MapperType)
                {
                    case MappingRuleTypes.USERATTRIBUTE:
                        <span>@Global.UserAttribute</span>
                        break;
                    case MappingRuleTypes.USERPROPERTY:
                        <span>@Global.UserProperty</span>
                        break;
                    case MappingRuleTypes.SUBJECT:
                        <span>@Global.Subject</span>
                        break;
                }
            </Template>
        </RadzenDataGridColumn>
        <RadzenDataGridColumn TItem="SelectableScopeMapper" Filterable="false" Sortable="false" Width="80px" TextAlign="TextAlign.Center">
            <Template Context="data">
                <SidAuthorizeView Roles=@($"/scopes/manage")>
                    <Authorized>
                        <RadzenButton Icon="more_vert" Click="@(args => ShowMoreContextMenu(data, args))" />
                    </Authorized>
                </SidAuthorizeView>
            </Template>
        </RadzenDataGridColumn>
    </Columns>
</RadzenDataGrid>


@code {
    bool selectAll = false;

    [Parameter]
    public SimpleIdServer.IdServer.Domains.Scope Scope { get; set; }

    protected override void OnAfterRender(bool firstRender)
    {
        base.OnAfterRender(firstRender);
        if (firstRender)
            SubscribeToAction<RemoveSelectedScopeMappersSuccessAction>((act) =>
            {
                notificationService.Notify(new NotificationMessage { Severity = NotificationSeverity.Success, Summary = Global.SelectedScopesMappersRemoved });
                StateHasChanged();
            });
    }

    protected override void OnParametersSet()
    {
        base.OnParametersSet();
    }

    void ToggleChanged(bool isSelected, SelectableScopeMapper resourceMapper)
    {
        var act = new ToggleScopeMapperSelectionAction { IsSelected = isSelected, ScopeMapperId = resourceMapper.Value.Id };
        dispatcher.Dispatch(act);
    }

    void ToggleAll(bool isSelected)
    {
        var act = new ToggleAllScopeMapperSelectionAction { IsSelected = isSelected };
        dispatcher.Dispatch(act);
    }

    void ShowMoreContextMenu(SelectableScopeMapper mapper, MouseEventArgs args)
    {
        contextMenuService.Open(args, new List<ContextMenuItem>
        {
            new ContextMenuItem { Text = Global.Delete, Value = 1 }
        }, async (a) => {
        if (a.Value.Equals(1))
        {
            var mapperIds = scopeMappersState.Value.Mappers?.Where(c => c.IsSelected).Select(c => c.Value.Id)?.ToList();
            if (scopeMappersState.Value.Mappers.Any(r => mapperIds.Contains(r.Value.Id) && r.Value.MapperType == MappingRuleTypes.SUBJECT))
            {
                var isConfirmed = await dialogService.Confirm(Global.AreYouSure, Global.RemoveSubjectClaimMapper, new ConfirmOptions { OkButtonText = Global.Yes, CancelButtonText = Global.No });
                if (isConfirmed == null || !isConfirmed.Value) return;
            }

            var act = new RemoveSelectedScopeMappersAction { ScopeMapperIds = mapperIds, ScopeId = Scope.Id };
            dispatcher.Dispatch(act);
            contextMenuService.Close();
        }
    });
    }

    void RowRender(RowRenderEventArgs<SelectableScopeMapper> row)
    {
        const string className = "class";
        if (row.Data.IsNew)
            row.Attributes.Add(className, "new");
        else if (row.Data.IsSelected)
            row.Attributes.Add(className, "active");
        else if (row.Attributes.ContainsKey(className))
            row.Attributes.Remove(className);
    }

    async void AddMapper() 
    {
        await dialogService.OpenAsync<AddScopeMapperDialog>(Global.AddMapper, new Dictionary<string, object>
        {
            { "Scope", Scope }
        }, new DialogOptions
        {
            Width = "700px",
            Height ="512px",
            Resizable = true,
            Draggable = true
        });
    }
}